package com.ocm.resource.utils;


import com.ocm.resource.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Item;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * @program: com.ocm.product
 * @description
 * @author: hqy
 * @create: 2021-04-10 21:45
 **/
@Component
public class MinioUtils {


    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioConfig minioConfig;



    public String fileUpload(String fileName, InputStream inputStream) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException, RegionConflictException {
        //如果不存在 创建桶
//        boolean isExist = minioClient.bucketExists(minioConfig.getFolder());

//        if (isExist) {
//            System.out.println("Bucket already exists.");
//        } else {
//
//            minioClient.makeBucket(minioConfig.getFolder());
//        }

        minioClient.putObject(
                PutObjectArgs.builder().bucket(minioConfig.getFolder()).object(fileName)
                        .stream(inputStream, -1, 10485760)
                        .contentType("image/png")
                        .build());

        //文件访问路径
        String url = minioClient.getObjectUrl(minioConfig.getFolder(), fileName);
        return url;
    }

    //上传图片封装
    public String uploadImage(MultipartFile file, String fileName, String suffix) throws Exception {
        String url=fileUpload(fileName,file.getInputStream());
        //minioContentRepository.save(new MinioContent(null,fileName, minioConfig.getFolder(), String.valueOf(file.getSize()),url,suffix,file.getContentType(),new Timestamp(new Date().getTime())));
        return url;
    }

    //上传图片封装
    public String uploadImage(MultipartFile file, String suffix) throws Exception {
        String originalFilename = file.getOriginalFilename();
		assert originalFilename != null;
		String fileName= UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        String url= uploadImage(file,fileName,suffix);
        //minioContentRepository.save(new MinioContent(null,fileName, minioConfig.getFolder(), String.valueOf(file.getSize()),url,suffix,file.getContentType(),new Timestamp(new Date().getTime())));
        return url;
    }

    public void removeObject(String fileName)throws Exception {
        minioClient.removeObject(minioConfig.getFolder(),fileName);

    }

    public List<String> getAllObject()throws Exception {
        Iterable<Result<Item>> results = minioClient.listObjects(minioConfig.getFolder());
        List<String> objectList=new ArrayList<>();
        for (Result<Item> result : results) {
            Item item = result.get();
            objectList.add(item.objectName());
        }
        return objectList;
    }

    //批量删除
    public void deleteImageSe(Long[] fileId) throws Exception {

        for (Long id:fileId) {
            //MinioContent minioContent = minioContentRepository.getOne(id);
            //removeObject(minioContent.getKey());
            //minioContentRepository.deleteById(id);
        }

    }

    //单个文件删除
    public void deleteImageSe(Long fileId) throws Exception {

       // MinioContent minioContent = minioContentRepository.getOne(fileId);
        //removeObject(minioContent.getKey());
        //minioContentRepository.deleteById(fileId);


    }

    public String getBucket(){
        return minioConfig.getFolder();
    }

}
